<!--
 * @Author: your name
 * @Date: 2021-06-22 14:46:34
 * @LastEditTime: 2021-06-28 23:24:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \briup\day07\vue-admin-template\src\pages\product\List.vue
-->
<template>
  <div class="product-list">
    <!-- 添加按钮、模糊搜索、查询按钮 -->
    <div class="search">
      <div>
        <el-button class="btn" type="primary" @click="toAdd">添加</el-button>
      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="正常" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.productCategoryId"
            placeholder="请选择栏目"
            clearable
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="table">
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="id" label="产品编号" align="center" />
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column label="图片" align="center">
          <template slot-scope="scope">
            <!-- scope是当前temlate模板的作用域对象，row属性上存放的是当前行的数据对象 -->
            <el-image
              style="width: 30px; height: 20px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" align="center" />
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === '正常' ? 'success' : 'danger'"
            >{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category.name" label="所属栏目" align="center" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              style="color: green"
              @click="toEdit(scope.row)"
            >编辑</el-button>
            <!-- 隐藏状态按钮 -->
            <!-- <el-button v-if="scope.row.status==='下架'" @click="toOnline(scope.row.id)" type="text" size="small" style="color:red">上架</el-button>
            <el-button v-else @click="toOffline(scope.row.id)" type="text" size="small" style="color:red">下架</el-button> -->
            <!-- 禁用状态按钮 -->
            <el-button
              :disabled="scope.row.status === '正常'"
              type="text"
              size="small"
              @click="toOnline(scope.row.id)"
            >上架</el-button>
            <el-button
              :disabled="scope.row.status === '下架'"
              type="text"
              size="small"
              @click="toOffline(scope.row.id)"
            >下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-div">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 模态框 对话框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form ref="ruleForm" :model="form" :rules="rules" size="medium">
        <el-form-item
          label="产品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="所属栏目"
          :label-width="formLabelWidth"
          prop="productCategoryId"
        >
          <el-select
            v-model="form.productCategoryId"
            placeholder="所属栏目"
            clearable
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model.number="form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input
            v-model="form.description"
            autocomplete="off"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery } from '@/api/proCategory'
import {
  pageQuery as pageQueryPro,
  saveOrUpdate,
  offline,
  online
} from '@/api/product'
import { showFileURL, uploadFileURL } from '@/utils/config'

export default {
  data() {
    return {
      // 产品栏目的数据,页面一上来，就发送请求，请求所有的产品栏目数据，设置到categoryData。
      categoryData: [],
      // 模糊搜索表单的数据
      searchForm: {
        name: '',
        status: '',
        productCategoryId: ''
      },
      // 表格展示的数据
      tableData: [],
      // 分页参数
      params: {
        page: 1,
        pageSize: 10
      },
      // 总条数
      total: 0,
      // 加载
      loading: false,
      // 模态框的显示与隐藏
      visible: false,
      // 表单数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: '80px',
      // 模态框的标题
      title: '',
      // 图片url
      imageUrl: '',
      showFileURL,
      uploadFileURL,
      // 校验规则
      rules: {
        name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        productCategoryId: [
          { required: true, message: '请选择所属栏目', trigger: 'change' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
        ],
        photo: [
          { required: true, message: '请上传封面图片', trigger: 'change' }
        ]
      }
    }
  },
  computed: {},
  watch: {
    // 深度监听分页参数
    params: {
      handler() {
        this.querytableData()
      },
      deep: true
    }
  },
  created() {
    //   发请求
    this.queryCategoryData()
    this.querytableData()
  },
  mounted() {},
  methods: {
    //   获取产品分类数据
    async queryCategoryData() {
      const res = await pageQuery({ page: 1, pageSize: 100 })
      //   console.log(res.data.list);
      this.categoryData = res.data.list
    },
    // 分页模糊获取产品数据
    async querytableData() {
      this.loading = true
      // 处理数据
      const temp = {
        ...this.params,
        ...this.searchForm
      }
      // 遍历对象
      for (const key in temp) {
        // key是一个变量，代表的属性名
        // key是属性名,temp[key]是属性值
        // console.log(key,temp[key]);
        // 删除对象属性
        if (!temp[key]) {
          delete temp[key]
        }
      }
      const res = await pageQueryPro(temp)
      // 加载完毕
      this.loading = false
      this.tableData = res.data.list
      this.total = res.data.total
    },
    // 查询按钮点击事件处理程序
    toSearch() {
      this.querytableData()
    },
    // 每页显示的条数发生变化时的事件处理程序
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params = {
        page: 1,
        pageSize: val
      }
    },
    // 当前页码发生变化时的事件处理程序
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.page = val
    },
    // 添加按钮事件处理程序
    toAdd() {
      this.queryCategoryData()
      // 清空表单数据
      this.form = {}
      this.imageUrl = ''
      this.visible = true
      this.title = '添加产品信息'
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      // console.log(res,"==图片上传成功之后的res");
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(this.imageUrl);
      this.form.photo = showFileURL + res.data.id
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 模态框确定按钮事件处理程序
    toSave() {
      // 获取dom的值，对值进行校验
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          // 校验通过，做自己的业务
          // console.log("校验通过");
          const res = await saveOrUpdate(this.form)
          // console.log(res,"-----");
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          this.querytableData()
          // this.toClose();
          this.visible = false
        } else {
          // 校验不通过
          return false
        }
      })
    },
    // 关闭模态框
    toClose() {
      // 重置表单校验
      this.$refs.ruleForm.resetFields()
      // 超时调用  在多少毫秒后执行函数
      // setTimeout(()=>{
      //   this.visible=false;
      // },100);
    },
    // 编辑按钮的事件处理程序
    toEdit(row) {
      this.queryCategoryData()
      // 清空表单数据
      this.form = { ...row }
      this.imageUrl = this.form.photo
      this.visible = true
      this.title = '编辑产品信息'
    },
    // 上架产品
    async toOnline(id) {
      const res = await online({ id })
      this.$notify.success({
        title: '成功',
        message: res.message
      })
      this.querytableData()
    },
    // 下架产品
    async toOffline(id) {
      const res = await offline({ id })
      this.$notify.success({
        title: '成功',
        message: res.message
      })
      this.querytableData()
    }
  }
}
</script>
<style lang="scss" scoped>
/* scss less css 预处理器 */
.search {
  display: flex;
  .btn {
    margin-right: 10px;
  }
}
</style>
